package com.semp.jadoma.admin.action;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;

import com.semp.jadoma.admin.form.DogAddForm;
import com.semp.jadoma.admin.utils.Config;
import com.semp.jadoma.admin.utils.webapp.Forward;
import com.semp.jadoma.admin.utils.webapp.Session;
import com.semp.jadoma.core.model.Dog;
import com.semp.jadoma.core.service.DogService;

public class DogAddAction extends RootAction {

	private final static Logger logger = Logger.getLogger(DogAddAction.class);
	
	@Override
	public String executeChild(ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		DogAddForm dogAddForm = (DogAddForm) form;
		String dateAsString = dogAddForm.getBirthDay();
		Date birthDay;
		try {
			birthDay = Config.DATE_FORMAT_J.parse(dateAsString);
		} catch (RuntimeException e) {
			logger.error("Wrong date format", e);
			birthDay = new Date();
		}
		
		Dog createdDog = DogService.getInstance().createDog(
				dogAddForm.getName(),
				dogAddForm.getNickName(),
				birthDay,
				dogAddForm.getColor(),
				dogAddForm.getPeel(),
				dogAddForm.getSex(),
				dogAddForm.getSize(),
				dogAddForm.getWeight());
		
		logger.info("Dog: " + dogAddForm.getName() + " created");
		
		request.setAttribute(Session.BEAN_DOG, createdDog);		
		return Forward.SUCCESS;
	}

}
